package com.mhr.ai.cr.settings

import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.components.*
import com.intellij.util.ui.FormBuilder
import com.mhr.ai.cr.provider.AIProviderConfig
import com.mhr.ai.cr.provider.AIProviderFactory
import java.awt.BorderLayout
import javax.swing.*

/**
 * AI 代码审核设置界面
 * 支持多AI提供商配置
 */
class AISettingsConfigurable(private val project: Project) : Configurable {
    
    private val settings = AISettingsState.getInstance(project)
    
    // UI 组件
    private val enabledCheckBox = JBCheckBox("启用 AI 代码审核")
    private val autoReviewCheckBox = JBCheckBox("自动审核代码变更")
    
    private val providerComboBox = ComboBox<AIProviderFactory.ProviderType>()
    
    // 阿里云通义千问配置
    private val dashScopeApiKeyField = JBPasswordField()
    private val dashScopeModelComboBox = ComboBox<String>()
    private val dashScopeBaseUrlField = JBTextField()
    
    // DeepSeek配置
    private val deepSeekApiKeyField = JBPasswordField()
    private val deepSeekModelComboBox = ComboBox<String>()
    private val deepSeekBaseUrlField = JBTextField()
    
    private val temperatureSlider = JSlider(0, 100, 70)
    private val maxTokensSpinner = JSpinner(SpinnerNumberModel(2000, 100, 10000, 100))
    private val timeoutSpinner = JSpinner(SpinnerNumberModel(30, 5, 300, 5))
    
    private val reviewLanguageComboBox = ComboBox<String>()
    private val reviewLevelComboBox = ComboBox<String>()
    
    private val testButton = JButton("测试连接")
    private val statusLabel = JLabel()
    
    override fun getDisplayName(): String = "AI 代码审核"
    
    override fun createComponent(): JComponent {
        initializeComponents()
        setupEventListeners()
        
        return FormBuilder.createFormBuilder()
            .addComponent(createBasicSettingsPanel())
            .addVerticalGap(10)
            .addComponent(createProviderSettingsPanel())
            .addVerticalGap(10)
            .addComponent(createAdvancedSettingsPanel())
            .addVerticalGap(10)
            .addComponent(createTestPanel())
            .addComponentFillVertically(JPanel(), 0)
            .panel
    }
    
    private fun initializeComponents() {
        // 初始化提供商下拉框
        AIProviderFactory.getSupportedProviders().forEach { provider ->
            providerComboBox.addItem(provider)
        }
        
        // 初始化模型下拉框
        initializeModelComboBoxes()
        
        // 初始化审核语言
        reviewLanguageComboBox.addItem("zh")
        reviewLanguageComboBox.addItem("en")
        
        // 初始化审核级别
        reviewLevelComboBox.addItem("basic")
        reviewLevelComboBox.addItem("standard")
        reviewLevelComboBox.addItem("strict")
        
        // 设置温度滑块
        temperatureSlider.majorTickSpacing = 25
        temperatureSlider.minorTickSpacing = 5
        temperatureSlider.paintTicks = true
        temperatureSlider.paintLabels = true
    }
    
    private fun setupEventListeners() {
        // 测试连接按钮
        testButton.addActionListener {
            testConnection()
        }
    }
    
    private fun initializeModelComboBoxes() {
        // 初始化DashScope模型
        dashScopeModelComboBox.removeAllItems()
        AIProviderFactory.getProvider(AIProviderFactory.ProviderType.DASHSCOPE)?.getSupportedModels()?.forEach { model ->
            dashScopeModelComboBox.addItem(model.id)
        }
        
        // 初始化DeepSeek模型
        deepSeekModelComboBox.removeAllItems()
        AIProviderFactory.getProvider(AIProviderFactory.ProviderType.DEEPSEEK)?.getSupportedModels()?.forEach { model ->
            deepSeekModelComboBox.addItem(model.id)
        }
    }
    
    private fun createBasicSettingsPanel(): JPanel {
        return JPanel(BorderLayout()).apply {
            border = BorderFactory.createTitledBorder("基本设置")
            add(FormBuilder.createFormBuilder()
                .addComponent(enabledCheckBox)
                .addComponent(autoReviewCheckBox)
                .panel, BorderLayout.CENTER)
        }
    }
    
    private fun createProviderSettingsPanel(): JPanel {
        val mainPanel = JPanel(BorderLayout())
        
        // 当前提供商选择
        val currentProviderPanel = JPanel(BorderLayout()).apply {
            border = BorderFactory.createTitledBorder("当前使用的提供商")
            add(FormBuilder.createFormBuilder()
                .addLabeledComponent("选择提供商:", providerComboBox)
                .panel, BorderLayout.CENTER)
        }
        
        // 阿里云通义千问配置
        val dashScopePanel = JPanel(BorderLayout()).apply {
            border = BorderFactory.createTitledBorder("阿里云通义千问配置")
            add(FormBuilder.createFormBuilder()
                .addLabeledComponent("API 密钥:", dashScopeApiKeyField)
                .addLabeledComponent("模型:", dashScopeModelComboBox)
                .addLabeledComponent("Base URL (可选):", dashScopeBaseUrlField)
                .panel, BorderLayout.CENTER)
        }
        
        // DeepSeek配置
        val deepSeekPanel = JPanel(BorderLayout()).apply {
            border = BorderFactory.createTitledBorder("DeepSeek配置")
            add(FormBuilder.createFormBuilder()
                .addLabeledComponent("API 密钥:", deepSeekApiKeyField)
                .addLabeledComponent("模型:", deepSeekModelComboBox)
                .addLabeledComponent("Base URL (可选):", deepSeekBaseUrlField)
                .panel, BorderLayout.CENTER)
        }
        
        val helpLabel = JLabel("<html><small>💡 提示：<br>" +
                "• 阿里云通义千问：需要在阿里云控制台获取API密钥<br>" +
                "• DeepSeek：需要在DeepSeek官网注册并获取API密钥<br>" +
                "• 可以同时配置多个提供商，在上方选择当前使用的提供商</small></html>")
        
        mainPanel.add(FormBuilder.createFormBuilder()
            .addComponent(currentProviderPanel)
            .addVerticalGap(5)
            .addComponent(dashScopePanel)
            .addVerticalGap(5)
            .addComponent(deepSeekPanel)
            .addVerticalGap(5)
            .addComponent(helpLabel)
            .panel, BorderLayout.CENTER)
        
        return mainPanel
    }
    
    private fun createAdvancedSettingsPanel(): JPanel {
        val temperaturePanel = JPanel(BorderLayout()).apply {
            add(temperatureSlider, BorderLayout.CENTER)
            add(JLabel("${temperatureSlider.value / 100.0}"), BorderLayout.EAST)
        }
        
        temperatureSlider.addChangeListener {
            (temperaturePanel.getComponent(1) as JLabel).text = "${temperatureSlider.value / 100.0}"
        }
        
        return JPanel(BorderLayout()).apply {
            border = BorderFactory.createTitledBorder("高级设置")
            add(FormBuilder.createFormBuilder()
                .addLabeledComponent("温度:", temperaturePanel)
                .addLabeledComponent("最大令牌数:", maxTokensSpinner)
                .addLabeledComponent("超时时间(秒):", timeoutSpinner)
                .addLabeledComponent("审核语言:", reviewLanguageComboBox)
                .addLabeledComponent("审核级别:", reviewLevelComboBox)
                .panel, BorderLayout.CENTER)
        }
    }
    
    private fun createTestPanel(): JPanel {
        return JPanel(BorderLayout()).apply {
            border = BorderFactory.createTitledBorder("连接测试")
            add(FormBuilder.createFormBuilder()
                .addComponent(testButton)
                .addComponent(statusLabel)
                .panel, BorderLayout.CENTER)
        }
    }
    
    private fun testConnection() {
        testButton.isEnabled = false
        statusLabel.text = "正在测试连接..."
        
        SwingUtilities.invokeLater {
            try {
                val selectedProvider = providerComboBox.selectedItem as? AIProviderFactory.ProviderType
                if (selectedProvider == null) {
                    statusLabel.text = "❌ 请选择提供商"
                    return@invokeLater
                }
                
                // 获取当前提供商的配置
                val config = when (selectedProvider) {
                    AIProviderFactory.ProviderType.DASHSCOPE -> AIProviderConfig(
                        apiKey = String(dashScopeApiKeyField.password),
                        model = dashScopeModelComboBox.selectedItem as? String ?: "",
                        temperature = temperatureSlider.value / 100.0f,
                        maxTokens = maxTokensSpinner.value as Int,
                        timeout = timeoutSpinner.value as Int,
                        baseUrl = dashScopeBaseUrlField.text.takeIf { it.isNotBlank() }
                    )
                    AIProviderFactory.ProviderType.DEEPSEEK -> AIProviderConfig(
                        apiKey = String(deepSeekApiKeyField.password),
                        model = deepSeekModelComboBox.selectedItem as? String ?: "",
                        temperature = temperatureSlider.value / 100.0f,
                        maxTokens = maxTokensSpinner.value as Int,
                        timeout = timeoutSpinner.value as Int,
                        baseUrl = deepSeekBaseUrlField.text.takeIf { it.isNotBlank() }
                    )
                }
                
                val provider = AIProviderFactory.getProvider(selectedProvider)
                if (provider != null) {
                    val success = provider.testConnection(config)
                    statusLabel.text = if (success) "✅ ${selectedProvider.displayName} 连接成功" else "❌ ${selectedProvider.displayName} 连接失败"
                } else {
                    statusLabel.text = "❌ 未找到提供商"
                }
            } catch (e: Exception) {
                statusLabel.text = "❌ 连接失败: ${e.message}"
            } finally {
                testButton.isEnabled = true
            }
        }
    }
    
    override fun isModified(): Boolean {
        return enabledCheckBox.isSelected != settings.enabled ||
                autoReviewCheckBox.isSelected != settings.autoReview ||
                (providerComboBox.selectedItem as? AIProviderFactory.ProviderType)?.name != settings.currentProvider ||
                String(dashScopeApiKeyField.password) != settings.dashScopeApiKey ||
                (dashScopeModelComboBox.selectedItem as? String) != settings.dashScopeModel ||
                dashScopeBaseUrlField.text != settings.dashScopeBaseUrl ||
                String(deepSeekApiKeyField.password) != settings.deepSeekApiKey ||
                (deepSeekModelComboBox.selectedItem as? String) != settings.deepSeekModel ||
                deepSeekBaseUrlField.text != settings.deepSeekBaseUrl ||
                temperatureSlider.value / 100.0f != settings.temperature ||
                (maxTokensSpinner.value as Int) != settings.maxTokens ||
                (timeoutSpinner.value as Int) != settings.timeout ||
                (reviewLanguageComboBox.selectedItem as? String) != settings.reviewLanguage ||
                (reviewLevelComboBox.selectedItem as? String) != settings.reviewLevel
    }
    
    override fun apply() {
        settings.enabled = enabledCheckBox.isSelected
        settings.autoReview = autoReviewCheckBox.isSelected
        settings.currentProvider = (providerComboBox.selectedItem as AIProviderFactory.ProviderType).name
        
        // 保存阿里云通义千问配置
        settings.dashScopeApiKey = String(dashScopeApiKeyField.password)
        settings.dashScopeModel = dashScopeModelComboBox.selectedItem as? String ?: ""
        settings.dashScopeBaseUrl = dashScopeBaseUrlField.text
        
        // 保存DeepSeek配置
        settings.deepSeekApiKey = String(deepSeekApiKeyField.password)
        settings.deepSeekModel = deepSeekModelComboBox.selectedItem as? String ?: ""
        settings.deepSeekBaseUrl = deepSeekBaseUrlField.text
        
        settings.temperature = temperatureSlider.value / 100.0f
        settings.maxTokens = maxTokensSpinner.value as Int
        settings.timeout = timeoutSpinner.value as Int
        settings.reviewLanguage = reviewLanguageComboBox.selectedItem as? String ?: "zh"
        settings.reviewLevel = reviewLevelComboBox.selectedItem as? String ?: "standard"
    }
    
    override fun reset() {
        enabledCheckBox.isSelected = settings.enabled
        autoReviewCheckBox.isSelected = settings.autoReview
        
        // 设置当前提供商
        val providerType = settings.getCurrentProviderType()
        if (providerType != null) {
            providerComboBox.selectedItem = providerType
        }
        
        // 设置阿里云通义千问配置
        dashScopeApiKeyField.text = settings.dashScopeApiKey
        if (settings.dashScopeModel.isNotBlank()) {
            dashScopeModelComboBox.selectedItem = settings.dashScopeModel
        }
        dashScopeBaseUrlField.text = settings.dashScopeBaseUrl
        
        // 设置DeepSeek配置
        deepSeekApiKeyField.text = settings.deepSeekApiKey
        if (settings.deepSeekModel.isNotBlank()) {
            deepSeekModelComboBox.selectedItem = settings.deepSeekModel
        }
        deepSeekBaseUrlField.text = settings.deepSeekBaseUrl
        
        temperatureSlider.value = (settings.temperature * 100).toInt()
        maxTokensSpinner.value = settings.maxTokens
        timeoutSpinner.value = settings.timeout
        reviewLanguageComboBox.selectedItem = settings.reviewLanguage
        reviewLevelComboBox.selectedItem = settings.reviewLevel
        
        statusLabel.text = ""
    }
}